package com.aiti.lulian.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.LuLianRecruitmentDto;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.LuLianRecruitment;
import com.aiti.lulian.service.ILuLianEnterpriseService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.ILuLianRecruitmentService;
import com.aiti.lulian.vo.LuLianRecruitmentVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author WongMz
 * @CreateDate 2024-08-14
 * @Description: （技术改造、数字化转型、海外贸易）招募单控制层
 */
@Api(tags = "（技术改造、数字化转型、海外贸易）招募单控制层")
@RestController
@RequestMapping("/recruitment")
public class LuLianRecruitmentController extends WebController {

    protected final Logger logger = LoggerFactory.getLogger(LuLianRecruitmentController.class);

    @Autowired
    private ILuLianRecruitmentService recruitmentService;

    @Autowired
    private ILuLianEnterpriseUserService enterpriseUserService;

    @Autowired
    private ILuLianEnterpriseService enterpriseService;

    /**
     * @Author WongMz
     * @CreateDate 2024-08-15
     * @Description: 发布（技术改造、数字化转型、海外贸易）招募单
     */
    @ApiOperation("发布（技术改造、数字化转型、海外贸易）招募单")
    @PostMapping
    public Message save(@Validated @RequestBody LuLianRecruitment recruitment) {
        try {
            if (recruitment == null || BeanUtil.isEmpty(recruitment)) {
                logger.error("【save】方法新增异常：===》入参异常");
                return Fail("入参异常！");
            }
            //检查当前是否为已登录状态
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                recruitment.setCreator(userId);
            } else {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
            if (enterpriseIds == null || enterpriseIds.size() == 0) {
                enterpriseIds.add("0");
            }
            LambdaQueryWrapper<LuLianEnterprise> enterpriseWrapper = new LambdaQueryWrapper<>();
            enterpriseWrapper.in(LuLianEnterprise::getBaseId, enterpriseIds);
            int count = enterpriseService.count(enterpriseWrapper);
            if (count == 0) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            } else if (count == 1 && enterpriseUserList.size() > 1) {
                return Fail("该账号的企业关联记录存在多条！");
            } else if (count > 1) {
                return Fail("该账号关联了多个认证企业！");
            }
            //进行数据保存
            if (recruitmentService.save(recruitment)) {
                return Success("发布成功！");
            } else {
                return Fail("发布失败！");
            }
        } catch (Exception e) {
            logger.error("【save】方法新增异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-08-14
     * @Description: 查询（技术改造、数字化转型、海外贸易）招募单列表
     */
    @ApiOperation("查询（技术改造、数字化转型、海外贸易）招募单列表")
    @GetMapping("/list")
    public Message queryList(Integer pageNum, Integer pageSize, LuLianRecruitment recruitment) {
        try {
            if (pageNum == null || pageSize == null || recruitment == null || BeanUtil.isEmpty(recruitment)) {
                logger.error("【queryList】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
            Page<LuLianRecruitment> page = startPage(pageNum, pageSize);
            return Success(recruitmentService.queryList(page, recruitment));
        } catch (Exception e) {
            logger.error("【queryList】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-08-22
     * @Description: 查询四类合并后的招募单列表
     */
    @ApiOperation("查询四类合并后的招募单列表")
    @GetMapping("/all/list")
    public Message queryAllList(Integer pageNum, Integer pageSize, LuLianRecruitment recruitment) {
        try {
            if (pageNum == null || pageSize == null) {
                logger.error("【queryAllList】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
            Page<LuLianRecruitmentVo> page = startPage(pageNum, pageSize);
            return Success(recruitmentService.queryAllList(page, recruitment));
        } catch (Exception e) {
            logger.error("【queryAllList】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-08-29
     * @Description: （后台）查询四类合并后的招募单列表
     */
    @ApiOperation("（后台）查询四类合并后的招募单列表")
    @GetMapping("/backend/all/list")
    public Message queryAllListBackend(Integer pageNum, Integer pageSize, LuLianRecruitmentDto recruitmentDto) {
        try {
            if (pageNum == null || pageSize == null) {
                logger.error("【queryAllListBackend】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                recruitmentDto.setCreator(userId);
                Page<LuLianRecruitmentVo> page = startPage(pageNum, pageSize);
                return Success(recruitmentService.queryAllListBackend(page, recruitmentDto));
            } else {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
        } catch (Exception e) {
            logger.error("【queryAllListBackend】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-08-29
     * @Description: （后台）各条件查询的统计计数
     */
    @ApiOperation("（后台）各条件查询的统计计数")
    @GetMapping("/queryCount")
    public Message queryCount() {
        try {
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                return Message.success(recruitmentService.queryCount(userId));
            } else {
                System.out.println("------------------未登录------------------");
                return Message.fail("请先注册/登录！");
            }
        } catch (Exception e) {
            logger.error("【queryCount】方法查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-08-15
     * @Description: 根据baseId查询（技术改造、数字化转型、海外贸易）招募单详情
     */
    @ApiOperation("根据baseId查询（技术改造、数字化转型、海外贸易）招募单详情")
    @GetMapping("/{baseId}")
    public Message queryDetailsByBaseId(@PathVariable("baseId") String baseId) {
        try {
            if (StrUtil.isBlank(baseId)) {
                logger.error("【queryDetailsByBaseId】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
            return Success(recruitmentService.getById(baseId));
        } catch (Exception e) {
            logger.error("【queryDetailsByBaseId】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-08-15
     * @Description: 根据baseId修改（技术改造、数字化转型、海外贸易）招募单信息
     */
    @ApiOperation("根据baseId修改（技术改造、数字化转型、海外贸易）招募单详情")
    @PutMapping
    public Message updateByBaseId(@RequestBody LuLianRecruitment recruitment) {
        try {
            if (recruitment == null || BeanUtil.isEmpty(recruitment)) {
                logger.error("【updateByBaseId】方法更新异常：===》入参异常");
                return Fail("入参异常！");
            }
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                recruitment.setUpdateBy(userId);
            } else {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            if (recruitmentService.updateById(recruitment)) {
                return Success("修改成功！");
            } else {
                return Fail("修改失败！");
            }
        } catch (Exception e) {
            logger.error("【updateByBaseId】方法更新异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-08-15
     * @Description: 根据baseId删除（技术改造、数字化转型、海外贸易）招募单
     */
    @ApiOperation("根据baseId删除（技术改造、数字化转型、海外贸易）招募单")
    @DeleteMapping("/{baseId}")
    public Message deleteByBaseId(@PathVariable("baseId") String baseId) {
        try {
            if (StrUtil.isBlank(baseId)) {
                logger.error("【deleteByBaseId】方法删除异常：===》入参异常");
                return Fail("入参异常！");
            }
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            if (recruitmentService.removeById(baseId)) {
                return Success("删除成功！");
            } else {
                return Fail("删除失败！");
            }
        } catch (Exception e) {
            logger.error("【deleteByBaseId】方法删除异常：===》" + e);
            return Fail(e.getMessage());
        }
    }
}